package com.mv.service.security;
 
import java.util.HashSet;
import java.util.Set;
 
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import Export.CodeStorageContext.CodeStorageFactory;
import Models.User;
 
@Service("myUserDetailService")
public class UserDetailsServiceImpl implements UserDetailsService{
  
 private static GrantedAuthority authorityAdmin = new GrantedAuthorityImpl("ADMIN");
 private static GrantedAuthority authorityGuest = new GrantedAuthorityImpl("GUEST");
 
 public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
  User usr = CodeStorageFactory.LoadUserSimple(username);
  if(usr == null){
   throw new UsernameNotFoundException("Wrong username or password");
  }
  
  Set<GrantedAuthority> authorities = new HashSet<GrantedAuthority>();
  if(usr.GetIsAdmin())
	  authorities.add(authorityAdmin);
  else
	  authorities.add(authorityGuest);
  
  UserDetails matchingUser = new UserDetailsImpl(usr.getID(), username, usr.GetPassword(), authorities);
  
  return matchingUser;
 }
 
}